<?php
/**
 * TODO check if an item previously created could be reused
 *
 */


abstract class Yz_Controller_Templated
    extends Yz_Controller_Abstract
    implements Yz_Controller_Interface
{

    protected $viewClass = 'Yz_View_Template';
    protected $template;
    protected $templateName;

    /** null: use default
     *  false: prevent use of layout
     *  @var string|null|false
     */
    protected $layoutName;


    protected function selectTemplate($name=null)
    {
        debug();
        if (null === $name) {
            $name = $this->templateName;
            if (null === $name) {
                $name = lcfirst($this->shortClassName());
            }
        }
        $templateClass = $this->module->resolveLibrary('Template', $name);
        if (false === $templateClass) {
            throw new Yz_Exception("Template not found");
        }

        return new $templateClass($this->module);
    }


    protected function outputTemplate($template)
    {
        $router = $this->router;
        // assign variables to template
        if (static::$isAdmin) {
            // TODO what if the admin module has a different selector
            $admin = "admin/";
        } else {
            $admin = "";
        }
        $template->YzAdmin = $admin;
        $template->webRoot = $router->getWebRoot();
        $template->webPrefix = $router->getWebPrefix();
        $template->YzModule = $router->getModuleSelector();
        $template->YzOperation = $router->getControllerSelector();
        $template->YzLanguage = $router->getLanguageSelector();

        $layout = $this->selectLayout();
        if (false === $layout) {
            $layout = $template;
        } else {
            $layout->assignContent($template);
        }
        $this->getView()
            ->setTemplate($layout)
            ;
        return $this;
    }


    /**
     *  @param string|null $name
     *  @return Yz_Template_Layout_Interface
     */
    protected function selectLayout()
    {
        debug();
        $name = $this->layoutName;
        if (false === $name) {
            return false;
        }
        if (null === $name) {
            $name = static::$isAdmin ? 'Admin' : 'Default';
        }
        $class = $this->module->resolveLibrary('Template_Layout', $name);
        if (false === $class) {
            throw new Yz_Exception("Layout template not found");
        }
        return new $class($this->module);
    }

}
